/*
    3. Write a program in C to write multiple lines in a text file. 
    Test Data :
    Input the number of lines to be written : 4
    :: The lines are ::
    test line 1
    test line 2
    test line 3
    test line 4
    Expected Output :

    The content of the file test.txt is  :                                                                       
    test line 1                                                                                                   
    test line 2                                                                                                   
    test line 3                                                                                                   
    test line 4 
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LEN 1024

int main(void)
{
    int line, i;
    FILE *fp;
    char *filename = "test.txt";
    char *str = malloc(MAX_LEN);
    char ch;
    fpos_t pos;
    printf("Input the number of lines to be written : ");
    scanf("%d", &line);
    fp = fopen(filename, "w+");
    if(!fp){
        printf("Open file %s error!", filename);
        return -1;
    }
    fgetpos(fp, &pos);
    printf(":: The lines are ::\n");
    fflush(stdin);
    for(i = 0; i < line; i++){
        gets(str);
        fprintf(fp, "%s\n", str);
    }
    fsetpos(fp, &pos);
    printf("\nThe content of the file %s is  :\n", filename);
	while ((ch = fgetc(fp)) != EOF){
        putc(ch, stdout);
    }
    fclose(fp);

    return 0;
}
